import { login, getUserInfo, getUserDetailById } from '@/api/user.js'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth.js'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, data) {
      state.userInfo = { ...data }
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(context, data) {
      const res = await login(data)
      context.commit('setToken', res)
      setTimeStamp() // 将当前的最新时间写入缓存
    },
    async getUserInfo(context) {
      const res = await getUserInfo()
      const details = await getUserDetailById(res.userId)
      const data = { ...res, ...details }
      context.commit('setUserInfo', data)
      return data
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  }
}
